<template>
  <div>
    <KnHeader></KnHeader>
    <div class="left-container">
      <el-row class="tac">
        <el-col :span="4">
          <el-tree :data="categories" :props="defaultProps" default-expand-all @node-click="handleNodeClick"></el-tree>
        </el-col>
        <el-col :span="20" class="table-container">
          <el-row>
            <el-col :span="18">
              <el-button type="primary" @click="addEbook">新增</el-button>
            </el-col>
            <el-col :span="4">
              <el-input v-model="search" placeholder="请输入内容"></el-input>
            </el-col>
            <el-col :span="1" :offset="1">
              <el-button type="primary" icon="el-icon-search" @click="findByName">搜索</el-button>
            </el-col>
          </el-row>
          <el-table :data="tableData" style="width: 100%">

            <!-- 封面列 -->
            <el-table-column label="封面" width="180">
              <template slot-scope="scope">
                <img :src="scope.row.cover" :alt="scope.row.name + '的封面'" class="cover-image" />
              </template>
            </el-table-column>

            <!-- 名称列 -->
            <el-table-column prop="name" label="名称" width="180"></el-table-column>

            <!-- 分类一列 -->
            <el-table-column prop="category1IdName" label="分类一"></el-table-column>

            <!-- 分类二列 -->
            <el-table-column prop="category2IdName" label="分类二"></el-table-column>

            <!-- 文档数量列 -->
            <el-table-column prop="docCount" label="文档数量"></el-table-column>

            <!-- 阅读数列 -->
            <el-table-column prop="viewCount" label="阅读数"></el-table-column>

            <!-- 点赞数列 -->
            <el-table-column prop="voteCount" label="点赞数"></el-table-column>

            <!-- 操作列（编辑、修改、删除） -->
            <el-table-column label="操作" width="180">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="handleEdit(scope.row)">
                  文档编辑
                </el-button>
                <el-button type="text" size="small" @click="handleModify(scope.row)">
                  修改
                </el-button>
                <el-button type="text" size="small" @click="handleDelete(scope.row)">
                  删除
                </el-button>
              </template>
            </el-table-column>

          </el-table>
          <el-col :offset="4" class="block">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
              :current-page="currentPage4" :page-sizes="[5, 10, 15, 20]" :page-size="pageInfo.pageSize"
              layout="total, sizes, prev, pager, next, jumper" :total="pageInfo.total">
            </el-pagination>
          </el-col>
        </el-col>

      </el-row>

    </div>
    <el-dialog title="分类表单" :visible.sync="dialogVisible" width="50%" :before-close="handleClose">
      <el-form ref="form" v-model="form" label-width="80px">
        <el-form-item label="名称">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="分类">
          <el-cascader v-model="form.selectedOptions" placeholder="请选择" :options="options" :props="cascaderProps"
            clearable @change="handleChange"></el-cascader>
        </el-form-item>
        <el-form-item label="上传封面">
          <el-upload class="avatar-uploader" :action="serverUrl" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="cover"
              :src="cover || 'http://39.105.159.64:9000/hero-nintendo/2025/04/6b0f52e7-6264-40d7-8c3e-425ffb3c32b8.png'"
              class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="阅读数">
          <el-input v-model="form.viewCount"></el-input>
        </el-form-item>
        <el-form-item label="点赞数">
          <el-input v-model="form.voteCount"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import KnHeader from "@/components/KnHeader";
import NavigationBarVue from '@/views/NavigationBarVue.vue'
import { getCategories } from "@/apis/categoryApi";
import { saveEbook, getEbooksByPage, getEbookById, updateEbook, deleteById } from '@/apis/ebooks'
export default {
  name: "EbookVue",
  components: {
    KnHeader,
    NavigationBarVue
  },


  data() {
    return {
      // serverUrl: 'http://localhost:8080/file/upload',
      serverUrl: '/api/file/upload',
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      categories: [],
      selectedOptions: [],
      dialogVisible: false,
      form: {},
      tableData: [],
      currentPage4: 4,
      value: [],
      options: [],
      cascaderProps: {
        checkStrictly: true, // 允许选择任意一级，不强制选择到最后一级
        expandTrigger: 'hover', // 可选 'hover' 或 'click'
        // 如果你的数据结构与标准级联结构不同，可以使用 `value-key` 指定唯一键
        value: 'id',
        label: 'label'
      },
      cover: '',
      search: '',
      pageInfo: {},
      pageSize: 10,
      pageNum: 1
    }
  },
  mounted() {
  },
  methods: {
    handleNodeClick(data) {
      console.log(data.id);
      this.$router.push('/navigationBarVue/' + data.id)
    },
    /**
     * findByName
     */
    async findByName() {
      let findPo = {
        name: this.search,
        pageNum: 1,
        pageSize: 10
      }
      let res = await getEbooksByPage(findPo)
      console.log(res);
      this.pageInfo = res.data.data
      this.tableData = res.data.data.list
      console.log(this.tableData);
      console.log("===>", this.pageInfo);
    },
    async getEbooks() {
      let findPo = {
        search: this.search,
        pageNum: 1,
        pageSize: 10
      }
      let res = await getEbooksByPage(findPo)
      console.log(res);
      this.pageInfo = res.data.data
      this.tableData = res.data.data.list
      console.log(this.tableData);
      console.log("===>", this.pageInfo);

    },
    async getCategory() {
      let records = await getCategories()
      console.log(records)
      this.categories = records.data.data
      this.options = this.categories
    },
    async handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val
      let findEBookPo = {
        search: this.search,
        pageNum: this.pageNum,
        pageSize: val
      }
      let res = await getEbooksByPage(findEBookPo)
      console.log(res);
      this.pageInfo = res.data.data
      this.tableData = res.data.data.list
      console.log(this.tableData);
    },
    async handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageNum = val
      let findEBookPo = {
        search: this.search,
        pageNum: val,
        pageSize: this.pageSize
      }
      let res = await getEbooksByPage(findEBookPo)
      console.log(res);
      this.pageInfo = res.data.data
      this.tableData = res.data.data.list
      console.log(this.tableData);
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => { });
    },
    cancel() {
      this.dialogVisible = false
    },
    async save() {
      this.dialogVisible = false
      this.form.cover = this.cover
      console.log('form====>', this.form);
      if (this.form.id) {
        let res = await updateEbook(this.form)
        console.log(res);
        if (res.data.status === 200) {
          this.$message({
            message: '更新成功',
            type: 'success'
          })
          this.getEbooks()
        } else {
          this.$message({
            message: res.data.msg,
            type: 'error'
          })
        }
      } else {
        let res = await saveEbook(this.form)
        console.log('res===>', res);
        if (res.data.status === 200) {
          this.$message('保存成功', 'success')
          this.getEbooks()
        } else {
          this.$message({
            message: res.data.msg,
            type: 'error'
          })
      }
    }


  },
  addEbook() {
    this.dialogVisible = true
    this.form = {}
  },
  handleChange(value) {
    console.log(value);
  },
  handleAvatarSuccess(res, file) {
    console.log(res, file);
    this.cover = res.data
    this.form.cover = res.data
    // this.cover = URL.createObjectURL(file.raw);
  },
  beforeAvatarUpload(file) {
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      this.$message.error('上传头像图片大小不能超过 2MB!');
    }
    return isLt2M;
  },
  handleEdit(row) {
    // 编辑逻辑
    console.log('编辑', row);
    this.$router.push('/ebook/' + row.id)
  },
  async handleModify(row) {
    // 修改逻辑
    console.log('修改', row.id);
    let res = await getEbookById(row.id)
    this.dialogVisible = true
    this.form = res.data.data
    this.cover = res.data.data.cover
    this.form = { ...res.data.data, selectedOptions: [res.data.data.category1Id, res.data.data.category2Id] };
  },
  async handleDelete(row) {
    // 删除逻辑
    console.log('删除', row);
    let res = await deleteById(row)
    console.log(res);
    this.getEbooks()
  },
},
created() {
  this.getCategory()
  this.getEbooks()
},
}
</script>

<style scoped>
.cover-image {
  width: 80px;
  /* 调整宽度 */
  height: 80px;
  /* 调整高度 */
  object-fit: cover;
  /* 保持图片比例并覆盖整个区域 */
}

.table-container {
  padding: 15px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>